package net.lab1024.smartadmin.module.weapp.login;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import net.lab1024.smartadmin.common.constant.JudgeEnum;
import net.lab1024.smartadmin.module.system.employee.EmployeeService;
import net.lab1024.smartadmin.module.system.employee.constant.EmployeeStatusEnum;
import net.lab1024.smartadmin.module.system.employee.domain.bo.EmployeeBO;
import net.lab1024.smartadmin.module.system.employee.domain.dto.EmployeeDTO;
import net.lab1024.smartadmin.module.system.login.domain.RequestTokenBO;
import net.lab1024.smartadmin.module.weapp.login.domain.RequestWeappTokenBO;
import net.lab1024.smartadmin.module.weapp.users.domain.bo.WxUsersBO;
import net.lab1024.smartadmin.module.weapp.users.domain.dto.UsersAddDTO;
import net.lab1024.smartadmin.module.weapp.users.domain.vo.UsersVO;
import net.lab1024.smartadmin.module.weapp.users.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.UUID;

/**
 * [  ]
 *
 * @author yandanyang
 * @version 1.0
 * @company 1024lab.net
 * @copyright (c) 2019 1024lab.netInc. All rights reserved.
 * @date
 * @since JDK1.8
 */
@Slf4j
@Service
public class WeappLoginTokenService {

    /**
     * 过期时间一天
     */
    private static final int EXPIRE_SECONDS = 1 * 24 * 3600;
    /**
     * jwt加密字段
     */
    private static final String CLAIM_ID_KEY = "id";

    @Value("${jwt.key}")
    private String jwtKey;

    @Autowired
    private UsersService usersService;


    /**
     * 功能描述: 生成JWT TOKEN
     *
     * @param wxUser
     * @return
     * @auther 五千
     * @date 2021/3/10 0012 上午 10:08
     */
    public String generateToken(UsersVO wxUser) {
        Long uid = wxUser.getUid();
        /**将token设置为jwt格式*/
        String baseToken = UUID.randomUUID().toString();
        LocalDateTime localDateTimeNow = LocalDateTime.now();
        LocalDateTime localDateTimeExpire = localDateTimeNow.plusSeconds(EXPIRE_SECONDS);
        Date from = Date.from(localDateTimeNow.atZone(ZoneId.systemDefault()).toInstant());
        Date expire = Date.from(localDateTimeExpire.atZone(ZoneId.systemDefault()).toInstant());

        Claims jwtClaims = Jwts.claims().setSubject(baseToken);
        jwtClaims.put(CLAIM_ID_KEY, uid);
        String compactJws = Jwts.builder().setClaims(jwtClaims).setNotBefore(from).setExpiration(expire).signWith(SignatureAlgorithm.HS512, jwtKey).compact();

        if(wxUser.getOpenid() != null) {
            WxUsersBO wxUsersBO = usersService.getByOpenid(wxUser.getOpenid());
            RequestWeappTokenBO tokenBO = new RequestWeappTokenBO(wxUsersBO);
        }

        return compactJws;
    }

    /**
     * 功能描述: 根据登陆token获取登陆信息
     *
     * @param
     * @return
     * @auther wuqian
     * @date 2021/3/10 0012 上午 10:11
     */
    public RequestWeappTokenBO getUserTokenInfo(String token) {
        String openid = "";
        try {
            Claims claims = Jwts.parser().setSigningKey(jwtKey).parseClaimsJws(token).getBody();
            String idStr = claims.get(CLAIM_ID_KEY).toString();
            openid = idStr;
        } catch (Exception e) {
            log.error("getUserTokenInfo error:{}", e);
            return null;
        }

        WxUsersBO wxUsersBO = usersService.getByOpenid(openid);
        if (wxUsersBO == null) {
            return null;
        }

        return new RequestWeappTokenBO(wxUsersBO);
    }

}
